/******************************************************************************************************
Copyright (C) 2017 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals BaseConverter, NMRSpectrum, File, TextStream, settings, strings, Env, Dir, mainWindow, MessageBox, qsTr, Application*/
/*jslint plusplus: true, indent: 4*/

function Custom1DCsvConverter() {
	"use strict";
	BaseConverter.call(this);
	this.exportFileFilter = "NMR 1D Custom CSV (*.csv *.txt)";
}

Custom1DCsvConverter.prototype = new BaseConverter();

Custom1DCsvConverter.prototype.wantsExport = function (aPageItems) {
	"use strict";
	var i, spec;

	for (i = 0; i < aPageItems.length; i++) {
		if (aPageItems[i].name === "NMR Spectrum") {
			spec = new NMRSpectrum(aPageItems[i]);
			if (spec.isValid() && spec.dimCount === 1) {
				return true;
			}
		}
	}
	return false;
};

Custom1DCsvConverter.prototype.exportItems = function (aPageItems, aFilename) {
	"use strict";
	var format, formats, decimals, dlg, reverse;

	decimals = settings.value("Custom1DCsvConverter/DecimalsPlaces", 6);
	reverse = settings.value("Custom1DCsvConverter/Reverse", false);
	format = settings.value("Custom1DCsvConverter/CurrentFormat", "{ppm}{tab}{real}{tab}{imag}");

	if (!Env.converterUseDefaultSettings) {
		dlg = Application.loadUiFile("ricares:WCustom1DCsvConverter.ui");
		dlg.widgets.sbDecimalPlaces.value = decimals;
		dlg.widgets.cmbFormat.items = settings.value("Custom1DCsvConverter/Formats", ["{ppm}{tab}{real}{tab}{imag}", "{ppm}{tab}{real}", "{hz}{tab}{real}{tab}{imag}", "{hz}{tab}{real}"]).map(function (aItem) {return aItem.replace(/\[/g, "{").replace(/\]/g, "}"); });
		dlg.widgets.cmbFormat.currentText = format;
		dlg.widgets.cbReverse.checked = reverse;

		mainWindow.restoreCursor();
		if (!dlg.exec()) {
			return 0;
		}

		format = dlg.widgets.cmbFormat.currentText;
		decimals = dlg.widgets.sbDecimalPlaces.value;
		reverse = dlg.widgets.cbReverse.checked;

		formats = dlg.widgets.cmbFormat.items.filter(function (aElement, aIndex) {return aElement !== format && aIndex <= 8; });
		formats.unshift(format);
		settings.setValue("Custom1DCsvConverter/Formats", formats);
	}

	settings.setValue("Custom1DCsvConverter/DecimalsPlaces", decimals);
	settings.setValue("Custom1DCsvConverter/Reverse", reverse);
	settings.setValue("Custom1DCsvConverter/CurrentFormat", format);

	mainWindow.setWaitCursor();
	try {
		Custom1DCsvConverter.formattedExport(aPageItems, aFilename, format.replace(/\{tab\}/g, "\t"), decimals, reverse);
	} finally {
		mainWindow.restoreCursor();
	}
};

Custom1DCsvConverter.formattedExport = function (aPageItems, aFilename, aFormat, aDecimals, aReverse) {
	"use strict";
	var file, strm, hz, dHz, i, pt, dPt, endPt, ppm, dPpm, spec,
		mapObj = {};

	try {
		file = new File(aFilename);
		if (file.open(File.WriteOnly)) {
			strm = new TextStream(file);
			for (i = 0; i < aPageItems.length; i++) {
				spec = new NMRSpectrum(aPageItems[i]);
				if (spec.isValid() && spec.dimCount === 1) {
					if (aReverse) {
						hz = spec.hz();
						dHz = spec.scaleWidth() / spec.count();
						pt = spec.count() - 1;
						dPt = -1;
						endPt = -1;
					} else {
						hz = spec.hz() + spec.scaleWidth();
						dHz = -spec.scaleWidth() / spec.count();
						pt = 0;
						dPt = 1;
						endPt = spec.count();
					}
					ppm = hz / spec.frequency();
					dPpm = dHz / spec.frequency();
					if (aReverse) {
						ppm += dPpm;
					}
					while (pt !== endPt) {
						mapObj.hz = hz.toFixed(aDecimals);
						mapObj.ppm = ppm.toFixed(aDecimals);
						mapObj.pts = pt;
						mapObj.real = spec.real(pt).toFixed(aDecimals);
						mapObj.imag = spec.imag(pt).toFixed(aDecimals);
						strm.writeln(aFormat.formatMap(mapObj));
						hz += dHz;
						ppm += dPpm;
						pt += dPt;
					}
					break;
				}
			}
		}
	} catch (e) {
		MessageBox.critical(qsTr("Exception found: {0}".format(e)));
	} finally {
		file.close();
	}
};

Env.Converters.push(new Custom1DCsvConverter());

Custom1DCsvConverter.Custom1DCsvConverterTest = function () {
	"use strict";
	var retVal = -1,
		cnv = new Custom1DCsvConverter(),
		pageItems = mainWindow.activeDocument.selection();

	if (cnv.wantsExport(pageItems)) {
		retVal = cnv.exportItems(pageItems, Dir.home() + "/Custom1DCsv.txt");
	}
	return retVal;
};
